jQuery(function ($) {

// Artifacts prices
var values = $.cookie('ap_trade_prices');

if (values == null) {
  values = $.ajax({url: "prices.txt", async: false}).responseText;
  values = $.trim(values.match(/(.*?)\n$/)[1]).split('\t');
  var x = new Date();
  x.setHours('23');
  x.setMinutes('59');
  x.setSeconds('59');
  $.cookie('ap_trade_prices', values.join('|'), {expires: x});
}
else {
  values = values.split('|');
}

// Adding artifacts rows
var artifacts, cods, table, position, level, actual;

artifacts = ['Basalt Monolith', 'Astrolabe', 'Celestial Prism', 'Crystal Rod', 'Charcoal Diamond', 'Memory Jar', 'Heart of Rana'];
cods      = ['1', '2', '4', '5', '8', '10', '15'];
table = $('#awplus_content table:eq(1)');

position = $('tr', table).length;

for (var i = position; i < values.length; i++) {
  level = parseInt((i - 3) / 7) + 1;
  actual = parseInt((i - 3) % 7);
  
  $('tr:last', table).after('<tr><td> <a style="color: #808080;" href="Stats/'+cods[actual]+'-'+level+'.html">&nbsp;'+artifacts[actual]+' '+level+'</a></td> <td align="right" style="color: #808080;">$'+values[i]+',00&nbsp;</td></tr>');
}

// Changing pp value
$('tr:eq(1) td:eq(1)', table).html('$'+values[1]+'&nbsp;');

// Cleaning vars
delete artifacts, cods, table, position, level, actual;


// Showing Price Graph

var graph_html = '<div style="background-color: #303030; font-weight: bold; text-align: center; margin: 0 1px 1px 1px; padding: 1px;">Price Graph - '+values[0]+'</div>';
graph_html += '<div id="ap_graph"></div>';
$('#awplus_content table:eq(0) > tbody > tr:eq(1) > td:eq(1)').append(graph_html);

$('tr:gt(0)', table).each(function() {
  var id = $('td:eq(0) a', this).attr('href').replace(/(Stats\/)(.*?)(\.html)$/, '$2');
  //console.log(id);
  $('td:eq(1)', this).wrapInner('<a class="ap_trade_graph" id="'+id+'" href="javascript: void(0);"></a>');
});

$('.ap_trade_graph').click(function() {
  var src = this.id;
  var title = $(this).parent('td').siblings('td').find('a:last').text();
  
  $('#ap_graph').html('<div style="background-color: #404040; margin: 0 1px 2px 1px; padding: 1px;">'+title+'</div><img src="Stats/'+src+'.sincebegin.png" width="100%" />');  
});

$('.ap_trade_graph:eq(1)').trigger('click');

});
